<template>
  <view class="container" :style="appThemeStyle">
    <view v-for="item in shopList" :key="item.shopId" class="cell-group">
      <view class="cell-item">
        <view class="label title">{{ item.shopName }}</view>
        <view class="value" />
      </view>
      <view v-for="channel in item.channels" :key="channel.id" class="cell-item">
        <view class="label">{{ channel.channelName }}</view>
        <view class="value">
          <u-switch
              v-model="channel.status"
              size="30"
              :active-value="1"
              :inactive-value="0"
              @change="updateShopStatus($event, item.shopId, channel)"
          />
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import { getShopsStatus, updateShopsStatus } from "@/api/message/settings";

export default {
  name: "open",
  data() {
    return {
      shopList: []
    }
  },
  onLoad() {
    this.getShopList()
  },
  methods: {
    /**
     * 获取数据列表
     */
    getShopList() {
      getShopsStatus().then(res => {
        const { data } = res
        this.shopList = data || []
      }).catch(reason => {})
    },
    /**
     * 更新门店渠道状态
     */
    updateShopStatus(value, shopId, channel) {
      const { id } = channel
      updateShopsStatus({
        id,
        status: value
      }).then(res => {
        const { data } = res
        if (data) {
          this.$toast('操作成功')
          return
        }
        this.restoreSwitch(value, shopId, channel)
      }).catch(reason => {
        this.restoreSwitch(value, shopId, channel)
      })
    },
    /**
     * 操作失败还原开关
     * @param value
     * @param shopId
     * @param channel
     */
    restoreSwitch(value, shopId, channel) {
      value = value === 1 ? 0 : 1
      this.shopList
          .find(shopItem => shopItem.shopId === shopId)
          .channels.find(channelItem => channelItem.id === channel.id)
          .status = value
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 24rpx;

  .cell-group {
    padding: 16rpx 24rpx;
    background: #fff;
    border-radius: 16rpx;
    margin-top: 16rpx;

    .cell-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx 0;
      border-bottom: 1rpx solid #eee;

      &:last-child {
        border: none;
      }

      .label {
        font-size: 28rpx;
        color: #333333;
      }

      .value {
        display: flex;
        align-items: center;
      }

      .title {
        font-size: 28rpx;
        color: #666666;
      }
    }
  }
}
</style>
